import axios from "axios";
import { useUserStoreHook } from "@/stores/modules/user";
import qs from "qs";
import { ElMessage, ElNotification } from "element-plus";

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
  paramsSerializer: (params) => {
    return qs.stringify(params);
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const accessToken = localStorage.getItem(TOKEN_KEY);
    if (accessToken) {
    //   config.headers.Authorization = accessToken;
      config.headers.token = accessToken;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'）, 如果是，直接返回响应对象
    if (
      response.config.responseType === "blob" ||
      response.config.responseType === "arraybuffer"
    ) {
      return response;
    }

    const { code, status, data, msg, info } = response.data;
    if (code === 200 || status === "200") {
      return response.data;
    }

    ElMessage.error(msg || info || "系统出错");
    return Promise.reject(new Error(msg || info || "Error"));
  },
  (error) => {
    // 异常处理
    if (error.response.data) {
      const { resCode, message, status } = error.response.data;
      if (resCode === "401") {
        ElNotification({
          title: "提示",
          message: "您的会话已过期，请重新登录",
          type: "info",
          duration: 5000,
        });
        useUserStoreHook()
          .resetToken()
          .then(() => {
            location.reload();
          });
      } else {
        ElMessage.error(message || "系统出错");
      }
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
